<template>
  <v-dialog v-model="dialogFormVisible" max-width="650" persistent>
    <v-card>
      <v-card-title>{{ title }}</v-card-title>
      <v-card-text>
        <v-data-table :loading="listLoading" :items="list" :headers="headers" item-key="tableName" show-select
          @update:select="setSelectRows" class="mt-4">
          <template #item.index="{ index }">
            {{ index + 1 }}
          </template>
        </v-data-table>
      </v-card-text>
      <v-card-actions>
        <v-spacer />
        <v-btn text @click="close">取 消</v-btn>
        <v-btn color="primary" :loading="listLoading" @click="save">确 定</v-btn>
      </v-card-actions>
    </v-card>
  </v-dialog>
</template>

<script setup lang="ts">
import { ref, reactive } from 'vue';
import { doImportTables, getTables } from '@/api/generator/tableManagement';
import { isNull } from '@/utils/validate';
import { message } from '@/utils/message';

const dialogFormVisible = ref(false);
const title = ref('');
const listLoading = ref(true);
const list = ref<any[]>([]);
const selectRows = ref<any[]>([]);

const headers = [
  { text: '序号', value: 'index', width: 80 },
  { text: '表名称', value: 'tableName', width: 240 },
  { text: '描述', value: 'tableComments' },
];

const emit = defineEmits(['fetchData']);

function show() {
  title.value = '导入数据库表';
  fetchData();
  dialogFormVisible.value = true;
}

function close() {
  dialogFormVisible.value = false;
  title.value = '';
  list.value = [];
  selectRows.value = [];
}

async function save() {
  if (selectRows.value.length > 0) {
    const tableNames = selectRows.value.map((item: any) => item.tableName).join(',');
    try {
      const { msg } = await doImportTables({ tableNames });
      message.success(msg || '导入成功');
      emit('fetchData');
      close();
    } catch (error) {
      message.error('导入失败');
    }
  } else {
    message.error('未选中任何行');
  }
}

function setSelectRows(rows: any[]) {
  selectRows.value = rows;
}

async function fetchData() {
  listLoading.value = true;
  try {
    const { data } = await getTables({});
    if (!isNull(data)) {
      list.value = data;
    }
  } catch (error) {
    message.error('获取数据失败');
  } finally {
    setTimeout(() => {
      listLoading.value = false;
    }, 300);
  }
}

defineExpose({ show });
</script>
